const mongoose = require('mongoose');
const Counter = require('./counter');
const dayjs = require('dayjs');
const { Schema } = mongoose

const CategorySchema = new Schema({
  category_id: {
    type: Number,
    unique: true,
    description: '分类id'
  },
  name: {
    type: String,
    unique: true,
    required: true,
    description: '分类名称'
  },
  code: {
    type: String,
    unique: true,
    required: true,
    description: '分类编码，用于系统标识'
  },
  description: {
    type: String, 
    required: false,
    default: '',
    description: '分类描述'
  },
  parent_id: {
    type: Number,
    default: null,
    description: '父分类id，顶级分类为null'
  },
  level: {
    type: Number,
    required: true,
    default: 1,
    description: '分类层级，从1开始'
  },
  sort_order: {
    type: Number,
    default: 0,
    description: '排序号，值越小越靠前'
  },
  image: {
    type: String,
    required: false,
    default: '',
    description: '分类图片URL'
  },
  icon: {
    type: String,
    required: false,
    default: '',
    description: '分类图标'
  },
  status: {
    type: String,
    enum: ['active', 'inactive'], // active:启用 inactive:禁用
    default: 'active',
    description: '分类状态'
  },
  is_visible: {
    type: Boolean,
    default: true,
    description: '是否可见'
  },
  created_at: {
    type: String, 
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String, 
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  }
})

CategorySchema.pre('save', async function(next) {
  if(this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'category_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      );
      this.category_id = counter.seq;
      next();
    } catch (error) {
      next(error);
    }
  } else {
    next();
  }
});

CategorySchema.pre('updateOne', async function(next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') });
  next();
});

const categoryModel = mongoose.model('category', CategorySchema, 'category')

module.exports = categoryModel